﻿using System;
using System.Collections.Generic;

namespace Macds.Core.Web
{
    /// <summary>
    /// In order to use this async request by seconds, you must extend the maxconnection default value
    ///     <system.net>
    ///         <connectionManagement>
    ///             <add address="*" maxconnection="5000"   />
    ///         </connectionManagement>
    ///     </system.net>
    /// </summary>
    public class RequestContainer : WebRequestBase, IRequestContainer
    {
        private Dictionary<string, RequestData> requestUrls;
        private Dictionary<string, RequestData> responseXmls;

        public RequestContainer()
        {
            this.requestUrls = new Dictionary<string, RequestData>();
            this.responseXmls = new Dictionary<string, RequestData>();
            RequestBySecond = 10;
        }

        public int RequestBySecond { get; set; }

        public void AddRequestData(string key, string url)
        {
            if (!this.requestUrls.ContainsKey(key))
            {
                this.requestUrls.Add(key,
                    new RequestData()
                    {
                        Key = key,
                        UrlData = url
                    });
            }
        }

        public Dictionary<string, RequestData> LoadRemoteData()
        {
            int sleepMs = Convert.ToInt32(1000 / RequestBySecond);
            foreach (var league in this.requestUrls.Keys)
            {
                System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(LoadDataAsync));
                t.Start(league);

                System.Threading.Thread.Sleep(sleepMs);
            }

            while (!IsDataCompleted())
            {
                System.Threading.Thread.Sleep(100);
            }

            return this.responseXmls;
        }

        private bool IsDataCompleted()
        {
            bool complete = false;
            int counter = 0;

            if (this.requestUrls.Count == this.responseXmls.Count)
            {
                foreach (var data in this.responseXmls)
                {
                    if (data.Value.isComplete)
                    {
                        counter++;
                    }
                }

                if (counter == this.responseXmls.Count)
                    complete = true;
            }

            return complete;
        }

        private void LoadDataAsync(object obj)
        {
            string key = (string)obj;
            RequestData urls = this.requestUrls[key];
            RequestData data = new RequestData { Key = key };

            this.responseXmls.Add(key, data);

            System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(LoadResponseData));
            t1.Start(new ResponseData() { Key = key, Url = urls.UrlData, TotalTryAfterError = 0 });
        }

        private void LoadResponseData(object obj)
        {
            try
            {
                ResponseData data = (ResponseData)obj;
                this.responseXmls[data.Key].UrlData = SendRequest(data.Url, "", Macds.Core.Web.RequestMethod.GET);
            }
            catch
            {
                ResponseData data = (ResponseData)obj;
                if (data.TotalTryAfterError < 3)
                {
                    data.TotalTryAfterError++;
                    LoadResponseData(data);
                }
                else
                {
                    this.responseXmls[data.Key].UrlData = "ERROR";
                }
            }
        }
    }
}
